package com.example.hblog.interceptors;

import com.example.hblog.Result;
import com.example.hblog.utils.HttpUtils;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String origin = request.getHeader("Origin");
        response.setHeader("Access-Control-Allow-Origin",origin);
        response.setHeader("Access-Control-Allow-Methods"," POST, GET,OPTIONS, DELETE");
//        response.setHeader("Access-Control-Max-Age","2592000");
        response.setHeader("Access-Control-Max-Age","2592000");
//        response.setHeader("Access-Control-Allow-Headers","x-requested-with,Authorization,token");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild, token, userToken");
//        response.setHeader("Access-Control-Allow-Headers","*");
//        response.setHeader("Access-Control-Expose-Headers","*");
        response.setHeader("Access-Control-Allow-Credentials","true");

        try{
            String userToken = request.getHeader("userToken");
            System.out.println(userToken);
            if (userToken!=null&&userToken.length()>0){
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("json/text;charset=utf-8");
            PrintWriter out = null;
            JSONObject resp = new JSONObject();
            resp.put("code", 601);
            resp.put("success", false);
            resp.put("message", "会话过期");
            out = response.getWriter();
            out.append(resp.toString());

        }
        return false;
    }
}
